#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
from socket import *
import os
import struct


Addr=('',8000)
BUFSIZE=1024
FileInfoSize=struct.calcsize('128s32sI8s')

SocketRecv=socket(AF_INET,SOCK_STREAM)
SocketRecv.bind(Addr)
SocketRecv.listen(5)

print "waitting ........"
while 1:
	conn,addr=SocketRecv.accept()
	print "send from" ,addr
	FileHead=conn.recv(FileInfoSize)
	filename,temp1,filesize,temp2=struct.unpack('128s32sI8s',FileHead)
	print filename,len(filename),type(filename)
	print filesize

	filename='new_'+filename.strip('\00')
	fp = open(filename,'wb')
	restsize=filesize

	while 1:
        	if restsize<BUFSIZE:
            		filedata=conn.recv(restsize)
	        else:
        	    	filedata=conn.recv(BUFSIZE)
        	if not filedata:
			break
       		fp.write(filedata)
        	restsize=restsize-len(filedata)
        	if restsize==0:
			break
	fp.close()
	conn.close()
	print filename + ' Finished !!!'
SocketRecv.close()

